<?php

namespace app\service\Web;

use app\model\CustomerCase;
use Exception;
use app\util\GlobalMsg;

class CustomerCaseService
{

    public static function getList(array $where = [], int $page = 0, int $pageSize = 0)
    {
        $customerCase = CustomerCase::with(['industry','scene']);
        if (!empty($where['is_show'])) {
            $customerCase = $customerCase->where('is_show', $where['is_show']);
        }
        if (!empty($where['is_top'])) {
            $customerCase = $customerCase->where('is_top', $where['is_top']);
        }
        if (!empty($where['lang'])) {
            $customerCase = $customerCase->where('lang', $where['lang']);
        }
        if (!empty($where['industry_id'])) {
            $customerCase = $customerCase->where('industry_id', $where['industry_id']);
        }
        if (!empty($where['scene_id'])) {
            $customerCase = $customerCase->where('scene_id', $where['scene_id']);
        }
        if (!empty($where['industry_ids'])) {
            $customerCase = $customerCase->whereIn('industry_id', explode(',',$where['industry_ids']));
        }
        if (!empty($where['scene_ids'])) {
            $customerCase = $customerCase->whereIn('scene_id',explode(',',$where['scene_ids']));
        }
        if (!empty($where['platform'])) {
            $customerCase = $customerCase->where('platform', $where['platform']);
        }
        if (!empty($where['keyword'])) {
            $customerCase = $customerCase->where(function($query) use($where) {
                $query
                    ->orWhere('title','like', '%'.$where['keyword'].'%')
                    ->orWhere('short_title', 'like', '%'.$where['keyword'].'%')
                    ->orWhere('content', 'like', '%'.$where['keyword'].'%')
                    ->orWhereHas('industry', function($q) use ($where) {
                        $q->where('name', 'like', '%'.$where['keyword'].'%');
                    })
                    ->orWhereHas('scene', function($q) use ($where) {
                        $q->where('name', 'like', '%'.$where['keyword'].'%');
                    });
            });
        }

        $count = $customerCase->count();

        if ($page > 0 && $pageSize > 0) {
            $customerCase = $customerCase->forPage($page, $pageSize);
        }

        $list = $customerCase->orderBy('is_top', 'asc')->orderBy('sort', 'asc')->orderBy('id', 'desc')->get()->toArray();

        return ['count' => $count, 'list' => $list];
    }

    public static function getOne(int $id = 0)
    {
        $info = CustomerCase::with(['industry','scene'])->where('id', $id)->first();
        if ($info == null) {
            throw new Exception(GlobalMsg::GET_HAS_NO);
        }
        return $info;
    }
}
